Huffman Tree 发表于 2018-12-13 | 更新于: 2019-02-16 | 分类于 Data Structure , Binary Tree | | 阅读数 字数统计: 684 | 阅读时长 ≈ 3 霍夫曼树的定义、实现及霍夫曼编码的求解与输出。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116#include <iostream>#include <cstring>#include <iomanip>using namespace std;struct HTNode { int weight;//权值 int parent;//指向父结点的指针域 int lchild;//左指针域 int rchild;//右指针域};class huffman_BT {private: HTNode *bt; char **hc; int nn;public: void select(HTNode *p, int k, int *i, int *j); void creat_hufm_BT(); int HuffmanCoding(); void HuffmanDisplay();};//在前k-1个结点中选择权值最小的两个结点i和jvoid huffman_BT::select(HTNode *p, int k, int *i, int *j) { int w, n = 0; while (n < k && (p + n)->parent != -1) n++;//寻找指向父结点指针为空的起始结点 w = (p + n)->weight; *i = n; while (n < k) { if ((((p + n)->weight) < w) && ((p + n)->parent == -1)) *i = n, w = (p + n)->weight; n++; } n = 0; while ((n < k) && ((p + n)->parent != -1) || (n == (*i))) n++; w = (p + n)->weight; *j = n; while (n < k) { if (((p + n)->weight < w) && (n != (*i)) && ((p + n)->parent == -1)) { *j = n; w = (p + n)->weight; } n++; } if ((*i) < (*j)) n = (*i), *i = *j, *j = n;}void huffman_BT::creat_hufm_BT() { HTNode *p; int k, i, j, m; cout << "请输入结点的个数:"; cin >> nn; m = nn * 2 - 1; bt = new HTNode[m]; p = bt; for (i = 0; i < m; i++) { p[i].weight = 0; p[i].parent = -1; p[i].lchild = -1; p[i].rchild = -1; } cout << "请依次输入权值:" << endl; for (i = 0; i < nn; i++) { cout << "请输入第" << i + 1 << "个权值:"; cin >> p[i].weight; } for (k = nn; k < m; k++) { select(p, k, &i, &j); (p + i)->parent = k; (p + j)->parent = k; (p + k)->lchild = i; (p + k)->rchild = j; (p + k)->weight = (p + i)->weight + (p + j)->weight; }}//从叶子到根逆向求每个字符的霍夫曼编码int huffman_BT::HuffmanCoding() { char *cd = new char[nn]; int start, c, f; hc = new char*[nn]; cd[nn - 1] = '\0'; for (int i = 0; i < nn; i++) { start = nn - 1; for (c = i, f = bt[i].parent; f != -1; c = f, f = bt[f].parent) { if (bt[f].lchild == c) cd[--start] = '0'; else cd[--start] = '1'; } hc[i] = new char[nn - start]; strcpy(hc[i], &cd[start]); } return 1;}//霍夫曼编码信息输出void huffman_BT::HuffmanDisplay() { HTNode *p; int k; p = bt; cout << "k" << setw(7) << "weight" << setw(7) << "parent" << setw(7) << "lchild" << setw(7) << "rchild" << endl; for (k = 0; k < 2 * nn - 1; k++) { cout << k << setw(7) << (p + k)->weight << setw(7) << (p + k)->parent << setw(7) << (p + k)->lchild << setw(7) << (p + k)->rchild << endl; } cout << "霍夫曼编码为:" << endl; for (k = 0; k < nn; k++) { cout << char('A' + k) << "(权值:" << p[k].weight << "):" << hc[k] << endl; }}int main() { huffman_BT hbt; hbt.creat_hufm_BT(); hbt.HuffmanCoding(); hbt.HuffmanDisplay(); return 0;} 本文作者: Einsturing 本文链接: http://einsturing.top/2018/12/13/霍夫曼树(Huffman Tree)/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!